package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.ContractProduct;
import cn.itcast.domain.cargo.ContractProductExample;
import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.UploadUtils;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("cargo/contractProduct")
public class ContractProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;
    @Reference
    private FactoryService factoryService;
    @Reference
    private ContractService contractService;
    @Autowired
    private UploadUtils uploadUtils;

    /**
     * 货物列表显示
     * 分析：
     *      1. 查询生产厂家
     *      2. 根据购销合同id，查询该购销合同下所有货物
     *      3. 存储购销合同id
     *      4. 返回
     */
    @RequestMapping("/list")
    public String list(
            String contractId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "5") int pageSize){
        //查询所有的工厂
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria factorycriteria = factoryExample.createCriteria();
        factorycriteria.andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",factoryList);

        //根据购销合同号查询所有的货物
        ContractProductExample contractProductExample = new ContractProductExample();
        ContractProductExample.Criteria contractProductCriteria = contractProductExample.createCriteria();
        contractProductCriteria.andContractIdEqualTo(contractId);
        PageInfo<ContractProduct> pageInfo = contractProductService.findByPage(contractProductExample, pageNum, pageSize);
        request.setAttribute("pageInfo",pageInfo);
        request.setAttribute("contractId",contractId);
        return "/cargo/product/product-list";
    }

    @RequestMapping("/edit")
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto){
        System.out.println("contractProduct ========================================= " + contractProduct);
        String company = getLoginCompanyId();
        String companyName = getLoginCompanyName();
        contractProduct.setCompanyId(company);
        contractProduct.setCompanyName(companyName);

        //1.判断是否具有id属性
        if(StringUtils.isEmpty(contractProduct.getId())) {
            /*需求：需要根据登陆用户显示当前登陆用户创建的购销合同。*/
            // 设置创建人
           // contract.setCreateBy(getLoginUser().getId());
            // 设置创建人部门
            //contract.setCreateDept(getLoginUser().getDeptId());
            // 新增
            if (productPhoto != null){
                try {
                    byte[] image = productPhoto.getBytes();
                    String file = uploadUtils.upload(image);
                    contractProduct.setProductImage(file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //2.没有id，保存
            contractProductService.save(contractProduct);
        }else{
            //3.有id，更新
            contractProductService.update(contractProduct);
        }
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractProduct.getContractId();
    }

    /**
     * 进入到修改界面
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id) {
        //货物信息
        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct",contractProduct);

        //查询所有生产厂家
        FactoryExample example2 = new FactoryExample();
        FactoryExample.Criteria criteria2 = example2.createCriteria();
        criteria2.andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(example2);
        request.setAttribute("factoryList",factoryList);
        return "cargo/product/product-update";
    }

    @RequestMapping("/delete")
    public String toUpdate(String id,String contractId) {
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }


    /**
     * 5. 上传货物（1）进入上传页面
     * http://localhost:8080/cargo/contractProduct/toImport.do?contractId=1
     */
    @RequestMapping("/toImport")
    public String toImport(String contractId){
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-import";
    }
    /**
     * 5. 上传货物（2）上传
     * <input type="file"  name="file">
     */
    @RequestMapping("/import")
    public String importExcel(String contractId,MultipartFile file) throws Exception {

        // 创建工作簿
        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        // 获取工作表
        Sheet sheet = workbook.getSheetAt(0);
        // 获取总行数
        int rows = sheet.getPhysicalNumberOfRows();
        // 注意：从第二行开始遍历
        for (int i = 1; i < rows; i++) {
            // 获取excel中每一行
            Row row = sheet.getRow(i);
            // 把excel的每一行封装为货物对象
            ContractProduct cp = new ContractProduct();
            cp.setFactoryName(row.getCell(1).getStringCellValue());
            cp.setProductNo(row.getCell(2).getStringCellValue());
            cp.setCnumber((int)row.getCell(3).getNumericCellValue());
            cp.setPackingUnit(row.getCell(4).getStringCellValue());
            cp.setLoadingRate(String.valueOf(row.getCell(5).getNumericCellValue()));
            cp.setBoxNum((int)row.getCell(6).getNumericCellValue());
            cp.setPrice(row.getCell(7).getNumericCellValue());
            cp.setProductDesc(row.getCell(8).getStringCellValue());
            cp.setProductRequest(row.getCell(9).getStringCellValue());
            // 设置购销合同id
            cp.setContractId(contractId);
            // 设置厂家id
            Factory factory = factoryService.findByName(cp.getFactoryName());
            if (factory != null) {
                cp.setFactoryId(factory.getId());
            }

            // 保存货物
            contractProductService.save(cp);
        }

        // 上传成功，去到货物列表
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }
}

